package HomeWork.Protot;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    public static <T> T createProxy(T target) {
        Class<?> targetClass = target.getClass();
        if (targetClass.isAnnotationPresent(YootkServiceProxy.class)) {
            YootkServiceProxy annotation = targetClass.getAnnotation(YootkServiceProxy.class);
            Class<?> proxyClass = annotation.proxyClass();
            try {
                Constructor<?> constructor = proxyClass.getConstructor(Object.class);
                InvocationHandler handler = (InvocationHandler) constructor.newInstance(target);
                return (T) Proxy.newProxyInstance(
                        target.getClass().getClassLoader(),
                        target.getClass().getInterfaces(),
                        handler);
            } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                     InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        InvocationHandler handler = new SimpleProxyHandler(target);
        return (T) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                handler);
    }
}